package com.vm.osm.business.controller;

import com.google.common.reflect.TypeToken;
import com.vm.osm.business.common.Constants;
import com.vm.osm.business.common.ControllerExceptionHandler;
import com.vm.osm.business.common.exception.BusinessException;
import com.vm.osm.business.dto.req.authConfig.ReqAddAuthConfig;
import com.vm.osm.business.dto.rsp.HttpRspResult;
import com.vm.osm.business.dto.rsp.authRule.*;
import com.vm.osm.business.dto.rsp.other.RspDepartmentAndStaff;
import com.vm.osm.business.entity.OsmAuthCode;
import com.vm.osm.business.entity.OsmDispatchRule;
import com.vm.osm.business.entity.OsmSysConfig;
import com.vm.osm.business.service.IOsmAuthService;
import com.vm.osm.business.service.IOsmDispatchRuleService;
import com.vm.osm.business.service.IOsmSysConfigService;
import com.vm.osm.business.util.ApiCallUtil;
import com.vm.osm.business.util.GsonUtil;
import com.vm.osm.business.util.UserDataUtil;
import com.vm.osm.business.util.UuidUtil;
import com.vma.eams.spring.boot.annotation.LogFunc;
import com.vma.eams.spring.boot.annotation.LogModule;
import com.vma.eams.spring.boot.log.LogCollector;
import io.swagger.annotations.*;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by chenzui on 2018/2/23.
 */
@RestController
@LogModule(type = "auth",name = "运维授权")
@RequestMapping("/v1.0")
@Api(value = "AuthController",description = "运维配置",tags = {"AuthController"})
public class AuthController extends ControllerExceptionHandler {
    private Logger LOG = Logger.getLogger(this.getClass());

    @Value("${eam_api_url}")
    private String eamApiUrl;

    @Autowired
    private IOsmAuthService osmAuthService;

    @Autowired
    private IOsmDispatchRuleService osmDispatchRuleService;

    @Autowired
    private IOsmSysConfigService osmSysConfigService;

    @ApiOperation(value = "查找运维配置",notes = "根据运维纬度以及运维对象")
    @RequestMapping(value = "/get_dispatches",method = RequestMethod.GET)
    public List<DispatchRule> getDispatchesByCond(
            @ApiParam(required=true, name="type", value="运维纬度") @RequestParam("type") String type,
            @ApiParam(name="obj_id", value="运维对象") @RequestParam(value = "obj_id",required = false) String objId,
            @ApiParam(name="auth_man", value="维护人姓名") @RequestParam(value = "auth_man",required = false) String authMan,
            @ApiParam(name="auth_obj_name", value="维护对象名称") @RequestParam(value = "auth_obj_name",required = false) String authObjName,HttpServletRequest request){
        LOG.info("查找运维配置");
        return osmDispatchRuleService.getDispatchesByCond(type,objId,authMan,authObjName,UserDataUtil.getUserSelectedEnterpriseId(request));
    }

    @ApiOperation(value = "查找运维配置",notes = "根据运维纬度以及运维对象")
    @RequestMapping(value = "/auth/page",method = RequestMethod.GET)
    public RspRulePage findPage(
            @ApiParam(required=true, name="type", value="运维纬度") @RequestParam("type") String type,
            @ApiParam(name="obj_id", value="运维对象") @RequestParam(value = "obj_id",required = false) String objId,
            @ApiParam(name="auth_man", value="维护人姓名") @RequestParam(value = "auth_man",required = false) String authMan,
            @ApiParam(name="auth_obj_name", value="维护对象名称") @RequestParam(value = "auth_obj_name",required = false) String authObjName,
            @ApiParam(required=true, name="page_num", value="分页数") @RequestParam("page_num") Integer pageNum,
            @ApiParam(required=true, name="page_size", value="分页大小") @RequestParam("page_size") Integer pageSize,HttpServletRequest request){
        LOG.info("查找运维配置");
        return osmDispatchRuleService.findPage(UserDataUtil.getUserSelectedEnterpriseId(request),type,objId,authMan,authObjName,pageNum,pageSize);
    }

    @ApiOperation(value = "查找运维纬度",notes = "查找运维纬度,顶部tab")
    @RequestMapping(value = "get_auth_range",method = RequestMethod.GET)
    public List<AuthType> getAuthRange(){
        LOG.info("查找运维纬度");
        return osmAuthService.findAll();
    }
    @LogFunc(type = "delete",name = "删除授权")
    @ApiOperation(value = "删除授权",notes = "删除授权,可支持批量。用英文逗号隔开")
    @RequestMapping(value = "/auth/delete/{id}",method = RequestMethod.DELETE)
    public void deleteAuth(@ApiParam(required=true, name="id", value="记录ID") @PathVariable("id") String ids){
        LOG.info("删除授权");
        String[] idArr = ids.split(",");
        for(int i=0;i<idArr.length;i++){
            OsmDispatchRule dispatchRule = osmDispatchRuleService.selectByPrimaryKey(idArr[i]);
            OsmAuthCode code = osmAuthService.selectByPrimaryKey(dispatchRule.getType());

            osmDispatchRuleService.deleteByPrimaryKey(idArr[i]);

            LogCollector.INSTANCE.put("删除",code.getTypeName()+"--"+dispatchRule.getAuthObjName());
        }
    }

    @LogFunc(type = "create",name = "新增授权")
    @ApiOperation(value = "新增运维授权",notes = "新增运维授权")
    @RequestMapping(value = "add_dispatch_config",method = RequestMethod.POST)
    public void addDispatchConfig(@RequestBody List<ReqAddAuthConfig> reqAddAuthConfigList,HttpServletRequest request){
        LOG.info("新增运维授权");
        Date date = new Date();
        for (ReqAddAuthConfig reqAddAuthConfig:reqAddAuthConfigList) {
            OsmDispatchRule dispatchRule = new OsmDispatchRule();
            dispatchRule.setId(UuidUtil.getRandomUuid());
            dispatchRule.setAuthMan(reqAddAuthConfig.getAuth_man());
            dispatchRule.setAuthObjName(reqAddAuthConfig.getAuth_obj_name());
            dispatchRule.setManId(reqAddAuthConfig.getMan_id());
            dispatchRule.setObjId(reqAddAuthConfig.getObj_id());
            dispatchRule.setType(reqAddAuthConfig.getType());
            dispatchRule.setCreateTime(date);
            dispatchRule.setUpdateTime(date);
            dispatchRule.setEnterpriseId(UserDataUtil.getUserSelectedEnterpriseId(request));
            dispatchRule.setStatus(new Byte("1"));
            osmDispatchRuleService.insert(dispatchRule);

            OsmAuthCode authType = osmAuthService.selectByPrimaryKey(reqAddAuthConfig.getType());
            LogCollector.INSTANCE.put("新增",authType.getTypeName()+"--"+dispatchRule.getAuthObjName());
        }
    }


    @ApiOperation(value = "查找组织部门树",notes = "查找组织部门树，调用设备管理接口")
    @RequestMapping(value = "get_org_list",method = RequestMethod.GET)
    public List<RspDeparmentTree> getOrgList(HttpServletRequest request) throws UnsupportedEncodingException {
        LOG.info("查找组织部门树");
        //企业编号
        String enterpriseId = UserDataUtil.getUserSelectedEnterpriseId(request);
        LOG.info("enterpriseId"+enterpriseId);
        // TODO: 2018/2/22  根据企业编号调用设备类型接口
        String getUrl = eamApiUrl+"/eam/v1.0/"+enterpriseId+"/department_trees?enterprise_name="+ URLEncoder.encode(UserDataUtil.getUserSelectedEnterpriseName(request),"UTF-8");
        HttpRspResult httpRspResult = ApiCallUtil.callGet(getUrl);
        if (httpRspResult == null){
            throw new BusinessException("获取设备类型异常");
        }
        if (httpRspResult.getHttp_status() != HttpStatus.SC_OK){
            throw new BusinessException("资产接口EAM-API:"+httpRspResult.getHttp_status());

        }
        Type listType = new TypeToken<ArrayList<RspDeparmentTree>>(){}.getType();

        List<RspDeparmentTree> rspDeparmentTrees = GsonUtil.fromJson(httpRspResult.getResponse_str(),listType);

        return rspDeparmentTrees;
    }

    @ApiOperation(value = "获取企业员工树",notes = "获取企业员工树，选员工使用")
    @RequestMapping(value = "/auth/enterprise_staff_trees",method = RequestMethod.GET)
    public List<RspDepartmentAndStaff> getDepartmentAndStaff(HttpServletRequest request){
        LOG.info("获取企业员工树");
        String mac = request.getHeader(Constants.MAC_KEY);
        //企业编号
        String enterpriseId = UserDataUtil.getUserSelectedEnterpriseId(request);
        String getUrl = eamApiUrl+"/eam/v1.0/common/"+enterpriseId+"/enterprise_staff_trees";

        HttpRspResult httpRspResult = ApiCallUtil.callGet(getUrl);
        if(httpRspResult == null){
            throw  new BusinessException("获取企业员工树异常");
        }

        if(httpRspResult.getHttp_status() != HttpStatus.SC_OK){
            throw new BusinessException("资产接口EAM-API:"+httpRspResult.getHttp_status());
        }
        Type listType = new TypeToken<ArrayList<RspDepartmentAndStaff>>(){}.getType();
        List<RspDepartmentAndStaff> rspDepartmentAndStaff = GsonUtil.fromJson(httpRspResult.getResponse_str(),listType);

        return rspDepartmentAndStaff;
    }


    @ApiOperation(value = "运维派单规则设置",notes = "运维派单规则设置")
    @RequestMapping(value = "/auth/save_cfg",method = RequestMethod.PUT)
    public void saveDispatchCfg( @ApiParam(required=true, name="dispatch", value="抢单开关") @RequestParam("dispatch") String dispatch,
                                 @ApiParam(required=true, name="condition", value="满足一个或者多个派单条件") @RequestParam("condition") String condition,
                                 HttpServletRequest request){

        osmSysConfigService.save(dispatch,condition,request);

    }

    @ApiOperation(value = "查询运维派单规则设置",notes = "查询运维派单规则设置")
    @RequestMapping(value = "/auth/config",method = RequestMethod.GET)
    public RspConfig getConfig(HttpServletRequest request){
        return osmSysConfigService.get(request);
    }
}

